package com.wxtl.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.wxtl.action.qo.LoginUser;
import com.wxtl.dao.base.HibernateBaseDao;
import com.wxtl.entity.Agent;
import com.wxtl.util.DataGridModel;
import com.wxtl.util.Page;
import com.wxtl.util.Status;

/**
 * AgentDao
 * @author liulin
 *
 */
@Repository
public class AgentDAO extends HibernateBaseDao {
	private static final Log log = LogFactory.getLog(AgentDAO.class);
	
	/**
	 * 根据agent对象查询
	 * @param dgm
	 * @param agent
	 * @return
	 */
	public Page query(DataGridModel dgm,Agent agent){
		//构建hql
		StringBuilder hql=new StringBuilder();
		List<Object> params=new ArrayList<Object>();
		hql.append("from Agent a where 1=1");
		if(agent.getAgentsn()!=null&&!"".equals(agent.getAgentsn())){
			params.add("%"+agent.getAgentsn()+"%");
			hql.append(" and a.agentsn like ?");
		}
		
		if(agent.getName()!=null&&!"".equals(agent.getName())){
			params.add("%"+agent.getName()+"%");
			hql.append(" and a.name like ?");
		}
		
		if(agent.getLinkman()!=null&&!"".equals(agent.getLinkman())){
			params.add("%"+agent.getLinkman()+"%");
			hql.append(" and a.linkman like ?");
		}
		
		if(agent.getTel()!=null&&!"".equals(agent.getTel())){
			params.add("%"+agent.getTel()+"%");
			hql.append(" and a.tel like ?");
		}
		
		if(agent.getArea()!=null&&!"".equals(agent.getArea())){
			params.add("%"+agent.getArea()+"%");
			hql.append(" and a.area like ?");
		}
		
		if(agent.getChannelMgr()!=null&&!"".equals(agent.getChannelMgr())){
			params.add("%"+agent.getChannelMgr()+"%");
			hql.append(" and a.channelMgr like ?");
		}
		
		if(agent.getState() !=null && agent.getState() != -1){
			params.add(agent.getState());
			hql.append(" and a.state=?");
		}
		
		hql.append(" order by a.regTime desc, a.agentsn");
		return super.queryForList(hql.toString(), params.toArray(new Object[]{}), dgm.getPage(), dgm.getRows());
	}
	
	public Agent load(int agentId){
		return (Agent) getHibernateTemplate().load(Agent.class, agentId);
	}
	
	public void delete(int[] ids){
		super.delete("agent","agentId", ids);
	}
	
	public Agent getAgentById(int id){
		return (Agent) getHibernateTemplate().get(Agent.class, id);
	}
	
	public Agent getAgentByNameAndPwd(LoginUser loginUser){
		String hql="from Agent a where a.agentsn=? and a.password=?";
		List<Agent> list= getHibernateTemplate().find(hql, new Object[]{loginUser.getUsername(),loginUser.getPassword()});
		if(list.size()>0)
			return list.get(0);
		return null;
	}
	
	/**
	 * 获取代理商
	 * @return
	 */
	public List<Agent> queryAllAgent(){
		String hql="from Agent a where a.state="+Status.AGENT_STATE_NORMAL;
		List<Agent> list= getHibernateTemplate().find(hql);
		return list;
	}
	
	
	
}